package com.azt.front.action.freemarker;

import com.azt.api.pojo.Content;
import com.azt.api.service.ContentService;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

/**
 * @ClassName PreAndNextContentDirective
 * @Description 获取资讯上下篇的模板
 * @author Snowler
 * @Date 2016年8月6日 上午11:57:48
 * @version 1.0.0
 */

@Component("pre_and_next")
public class PreAndNextContentDirective implements TemplateDirectiveModel {
	
	@Autowired
	private ContentService cs;

	@SuppressWarnings("rawtypes")
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		Integer contentId = DirectiveUtils.getInt("contentId", params, 1);
		Integer channelId = DirectiveUtils.getInt("channelId", params, 1);
		List<Integer> contentIds = cs.getContentIds(channelId);
		int indexOf = contentIds.indexOf(contentId);
		Integer pre = indexOf == 0 ?  null : contentIds.get(indexOf - 1);
		Integer next = indexOf == (contentIds.size() - 1) ? null : contentIds.get(indexOf + 1);
		
		Content preContent = null;
		Content nextContent = null;
		
		if(pre != null){
			preContent = cs.getContentById(pre);
		}
		if(next != null){
			nextContent = cs.getContentById(next);
		}
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put("pre", DEFAULT_WRAPPER.wrap(preContent));
		paramWrap.put("next", DEFAULT_WRAPPER.wrap(nextContent));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}

}
